// src/store/chat.ts
import { defineStore } from 'pinia'
import type { Message } from '../config/ai'
import { aiService } from '../services/ai'

export interface Conversation {
  id: string
  title: string
  messages: Message[]
  createdAt: number
}

export const useChatStore = defineStore('chat', () => {
  const messages = reactive<Message[]>([])
  const loading = ref(false)
  const isGenerating = ref(false)
  const canContinue = ref(false)
  const conversations = reactive<Conversation[]>([])
  const currentConversationId = ref<string | null>(null)


  // 获取当前会话
  const currentConversation = computed(() => 
    conversations.find((c: Conversation) => c.id === currentConversationId.value)
  )

  // 获取当前会话的消息
  const currentMessages = computed(() => 
    currentConversation.value?.messages || []
  )

  // 创建新会话
  const createNewConversation = () => {
    const newConversation: Conversation = {
      id: Date.now().toString(),
      title: '新会话',
      messages: [{
        role: 'assistant',
        content: '你好！我是 AI 助手，有什么我可以帮你的吗？'
      }],
      createdAt: Date.now()
    }
    conversations.unshift(newConversation)
    currentConversationId.value = newConversation.id
  }

  // 更新会话标题
  const updateConversationTitle = (id: string, firstMessage: string) => {
    const conversation = conversations.find((c: Conversation) => c.id === id)
    if (conversation) {
      // 使用第一条用户消息作为标题，限制长度
      conversation.title = firstMessage.slice(0, 20) + (firstMessage.length > 20 ? '...' : '')
    }
  }


  const STORAGE_KEY = 'chat-conversations'
    // 初始化时加载数据
    const savedConversations = localStorage.getItem(STORAGE_KEY)
    if (savedConversations) {
      conversations.push(...JSON.parse(savedConversations))
      currentConversationId.value = conversations[0]?.id || null
    }

    // 监听变化并保存
watch(
  conversations,
  (newConversations: Conversation[]) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(newConversations))
  },
  { deep: true }
)
  const stopGeneration = () => {
    isGenerating.value = false
    canContinue.value = true
    aiService.stopGeneration()
  }
  const addMessage = (message: Message) => {
    if (!currentConversationId.value) return
    
    const conversation = conversations.find((c: Conversation) => c.id === currentConversationId.value)
    if (conversation) {
      conversation.messages.push({
        ...message,
        timestamp: Date.now(),
      })
    }
  }

  const updateLastMessage = (content: string) => {
    if (!currentConversationId.value) return
    
    const conversation = conversations.find((c: Conversation) => c.id === currentConversationId.value)
    if (conversation && conversation.messages.length > 0) {
      const lastMessage = conversation.messages[conversation.messages.length - 1]
      if (lastMessage.role === 'assistant') {
        lastMessage.content = content
      }
    }
  }


  const continueGeneration = async () => {
    if (!canContinue.value) return

    loading.value = true
    isGenerating.value = true
    canContinue.value = false

    try {
      const response = await aiService.chatStream([], (text) => {
        if (isGenerating.value) {
          updateLastMessage(text)
        }
      }, true) // 标记为继续生成

      updateLastMessage(response)
    } catch (error: any) {
      console.error('Continue Generation Error:', error)
      if (error.message !== '生成已停止') {
        throw error
      }
    } finally {
      loading.value = false
      isGenerating.value = false
    }
  }
  const sendMessage = async (content: string) => {
    if (!content.trim()) return
    if (!currentConversationId.value) {
      createNewConversation()
    }

    const userMessage: Message = {
      role: 'user',
      content: content.trim(),
    }

    // 如果是会话的第一条用户消息，更新会话标题
    const conversation = conversations.find((c: Conversation) => c.id === currentConversationId.value)
    if (conversation && conversation.messages.length === 1) {
      updateConversationTitle(currentConversationId.value!, content)
    }

    // 新消息时重置继续生成状态
    canContinue.value = false
    
    // 添加用户消息
    addMessage(userMessage)
    
    loading.value = true
    isGenerating.value = true

    try {
      // 添加 AI 响应消息
      const assistantMessage: Message = {
        role: 'assistant',
        content: '',
      }
      addMessage(assistantMessage)

      // 获取消息历史
      const conversation = conversations.find((c: Conversation) => c.id === currentConversationId.value)
      const recentMessages = conversation?.messages.slice(-5).map(({ role, content }: Message) => ({
        role,
        content,
      })) || []

      const response = await aiService.chatStream(recentMessages, (text) => {
        if (isGenerating.value) {
          updateLastMessage(text)
        }
      })

      // 确保最后一条消息包含所有已生成的内容
      updateLastMessage(response)
    } catch (error: any) {
      console.error('Send Message Error:', error)
      const conversation = conversations.find((c: Conversation) => c.id === currentConversationId.value)
      if (conversation) {
        const lastMessage = conversation.messages[conversation.messages.length - 1]
        if (!lastMessage.content.trim()) {
          // 只有在消息完全为空时才删除
          conversation.messages.pop()
        }
      }
      if (error.message !== '生成已停止') {
        throw error
      }
    } finally {
      loading.value = false
      isGenerating.value = false
    }
  }


    // 删除会话
    const deleteConversation = (id: string) => {
      const index = conversations.findIndex((c: Conversation) => c.id === id)
      if (index !== -1) {
        conversations.splice(index, 1)
        if (currentConversationId.value === id) {
          currentConversationId.value = conversations[0]?.id || null
        }
      }
    }

  return {
    conversations,
    currentConversation,
    currentMessages,
    createNewConversation,
    updateConversationTitle,
    deleteConversation,
    messages,
    loading,
    isGenerating,
    canContinue,
    sendMessage,
    stopGeneration,
    continueGeneration,
    currentConversationId
  }
})